"use client";

import { useEffect, useState } from "react";
import "./index.css";
import { Flex, Menu, message } from "antd";
import { getQuestionBankVoByIdUsingGet } from "@/api/questionBankController";
import Title from "antd/es/typography/Title";
import { getQuestionVoByIdUsingGet } from "@/api/questionController";
import { Content } from "antd/es/layout/layout";
import Sider from "antd/es/layout/Sider";
import QuestionCard from "@/components/QuestionCard";
import Link from "next/link";
import { useRouter } from "next/navigation";

export default function BankQuestion({ params }) {
  const { questionBankId, questionId } = params;

  const [questionBank, setQuestionBank] = useState(undefined);
  const [question, setQuestion] = useState(undefined);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const router = useRouter();

  useEffect(() => {
    const fetchData = async () => {
      try {
        // 查询题库信息
        const bankRes = await getQuestionBankVoByIdUsingGet({
          id: questionBankId,
          needQueryQuestionList: true,
          pageSize: 20,
        });
        setQuestionBank(bankRes.data);

        // 查询题目信息
        const questionRes = await getQuestionVoByIdUsingGet({
          id: questionId,
        });
        setQuestion(questionRes.data);
      } catch (e) {
        setError(e);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [questionBankId, questionId]);

  if (loading) {
    return <div>加载中...</div>;
  }

  if (error || !questionBank || !question) {
    if (error) {
      message.info("请登陆后查看题目");
      router.push("/user/login");
      return;
    }
    return <div>查询失败</div>;
  }

  const questionListForMenu = questionBank.questionPage.records.map((q) => {
    return {
      label: (
        <Link href={`/questionBank/${questionBank.id}/question/${q.id}`}>
          {q.title}
        </Link>
      ),
      key: q.id,
    };
  });

  return (
    <div id={"bankQuestion"} className={"limit-min-height"}>
      <Flex gap={24}>
        <Sider width={240} theme={"light"}>
          <Title level={4}>{questionBank.title}</Title>
          <Menu items={questionListForMenu} selectedKeys={[question.id]} />
        </Sider>
        <Content>
          <QuestionCard question={question}></QuestionCard>
        </Content>
      </Flex>
    </div>
  );
}
